﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightAnimation
{
    public abstract class AnimationBase
    {
        private FrameworkElement _element;
        protected TimeSpan AnimationDuration;

        protected FrameworkElement Element
        {
            get { return _element; }
        }

        public event EventHandler AnimationCompleted;

        public AnimationBase(FrameworkElement element, TimeSpan duration)
        {
            AnimationDuration = duration;
            _element = element;
        }
        protected virtual void OnAnimationCompleted(EventArgs e)
        {
            if (AnimationCompleted != null)
                AnimationCompleted(this, e);
        }
        protected virtual string ResourceKey
        {
            get
            {
                return GetType().FullName;
            }
        }
        protected abstract Storyboard CreateStoryboard();
        protected abstract void ApplyValues(Storyboard storyboard);
        public virtual void Apply()
        {

            if (Element == null)

                throw new ArgumentNullException("element");
            Storyboard storyboard = null;
            if (Element.Resources.Contains(ResourceKey))
            {
                storyboard = Element.Resources[ResourceKey] as Storyboard;
                storyboard.Pause();
            }
            else
            {
                storyboard = CreateStoryboard();
                Element.Resources.Add(ResourceKey, storyboard);
                foreach (var timeline in storyboard.Children)
                {
                    Storyboard.SetTarget(timeline, Element);
                }
            }
            ApplyValues(storyboard);
            storyboard.Completed += OnStoryboardCompleted;
            storyboard.Begin();
        }
        protected virtual void OnStoryboardCompleted(object sender, EventArgs e)
        {
            OnAnimationCompleted(EventArgs.Empty);
        }

    }
}
